from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
import json
import uuid
from .models import Customer, Conversation, Message, KnowledgeBase
from ai_service.deepseek_service import deepseek_service


def index(request):
    """主页视图"""
    return render(request, 'chat/index.html')


@csrf_exempt
@require_http_methods(["POST"])
def chat_api(request):
    """聊天API"""
    try:
        data = json.loads(request.body)
        message = data.get('message', '').strip()
        session_id = data.get('session_id')
        
        if not message:
            return JsonResponse({
                'error': '消息不能为空',
                'status': 'error'
            }, status=400)
        
        # 如果没有session_id，生成一个新的
        if not session_id:
            session_id = str(uuid.uuid4())
        
        # 获取或创建客户
        customer, created = Customer.objects.get_or_create(
            session_id=session_id,
            defaults={
                'name': f'客户_{session_id[:8]}',
            }
        )
        
        # 获取或创建对话
        conversation, created = Conversation.objects.get_or_create(
            customer=customer,
            is_active=True,
            defaults={
                'title': message[:50] if len(message) > 50 else message
            }
        )
        
        # 保存用户消息
        user_message = Message.objects.create(
            conversation=conversation,
            message_type='user',
            content=message
        )
        
        # 先检查知识库
        ai_response = search_knowledge_base(message)
        
        # 如果知识库没有匹配的答案，调用DeepSeek
        if not ai_response:
            ai_response = deepseek_service.chat_with_deepseek(message, session_id)
        
        # 保存AI回复
        ai_message = Message.objects.create(
            conversation=conversation,
            message_type='ai',
            content=ai_response
        )
        
        return JsonResponse({
            'response': ai_response,
            'session_id': session_id,
            'status': 'success'
        })
        
    except json.JSONDecodeError:
        return JsonResponse({
            'error': '无效的JSON格式',
            'status': 'error'
        }, status=400)
    except Exception as e:
        return JsonResponse({
            'error': f'服务器错误: {str(e)}',
            'status': 'error'
        }, status=500)


def search_knowledge_base(query):
    """搜索知识库"""
    try:
        # 简单的关键词匹配
        knowledge_items = KnowledgeBase.objects.filter(
            is_active=True
        )
        
        for item in knowledge_items:
            keywords = [k.strip() for k in item.keywords.split(',')]
            for keyword in keywords:
                if keyword.lower() in query.lower():
                    return item.answer
        
        return None
    except Exception:
        return None


@api_view(['GET'])
def chat_history(request, session_id):
    """获取聊天历史"""
    try:
        customer = Customer.objects.get(session_id=session_id)
        conversations = Conversation.objects.filter(customer=customer)
        
        history = []
        for conv in conversations:
            messages = conv.messages.all()
            conv_data = {
                'conversation_id': conv.id,
                'title': conv.title,
                'created_at': conv.created_at,
                'messages': []
            }
            
            for msg in messages:
                conv_data['messages'].append({
                    'type': msg.message_type,
                    'content': msg.content,
                    'timestamp': msg.timestamp
                })
            
            history.append(conv_data)
        
        return Response({
            'history': history,
            'status': 'success'
        })
        
    except Customer.DoesNotExist:
        return Response({
            'error': '会话不存在',
            'status': 'error'
        }, status=404)


@csrf_exempt
@require_http_methods(["POST"])
def clear_session(request):
    """清除会话"""
    try:
        data = json.loads(request.body)
        session_id = data.get('session_id')
        
        if not session_id:
            return JsonResponse({
                'error': '会话ID不能为空',
                'status': 'error'
            }, status=400)
        
        # 清除DeepSeek会话上下文
        deepseek_service.clear_session(session_id)
        
        return JsonResponse({
            'message': '会话已清除',
            'status': 'success'
        })
        
    except Exception as e:
        return JsonResponse({
            'error': f'清除会话失败: {str(e)}',
            'status': 'error'
        }, status=500)
